package com.vclee.fast.integration.imserver;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vclee.fast.utils.task.ITask;
import com.vclee.fast.utils.task.TimerWheel;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class LockContainer {
    private static final Logger logger = LoggerFactory.getLogger(LockContainer.class);
    private static final Map<String,String> map = new ConcurrentHashMap<>();
    private static final TimerWheel wheel = new TimerWheel(1,32,"SEG_LOCK");

    private LockContainer(){

    }

    public static boolean tryLock(String name){
        for (int i = 0; i < 50; i++) {
            if(map.get("KEY_"+name)==null){
                break;
            }else {
                try {
                    Thread.sleep(80);
                }catch (InterruptedException e){
                    logger.warn("锁线程休眠异常:{}",e.getMessage());
                }
            }
        }
        boolean value = map.putIfAbsent("KEY_"+name,"VALUE_"+name)==null;
        if(value){
            wheel.addTask(new ITask() {
                @Override
                public void run() {
                    map.remove("KEY_"+name);
                }
            }, 240);
        }
        return value;
    }

    public static void unlock(String name){
        map.remove("KEY_"+name);
    }
}
